<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue'
  import { BasicModal, useModalInner } from '/@/components/Modal'
  import { BasicForm, useForm } from '/@/components/Form/index'
  import { passwordFormSchema } from './account.data'
  import { updatePassword } from '/@/api/demo/system'
  import { message } from 'ant-design-vue'
  import { useI18n } from 'vue-i18n'
  import { useMessage } from '/@/hooks/web/useMessage'

  export default defineComponent({
    name: 'PasswordModal',
    components: { BasicModal, BasicForm },
    setup() {
      const { createErrorModal } = useMessage()
      const rowId = ref('')
      const { t } = useI18n()
      const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
        labelWidth: 100,
        baseColProps: { span: 24 },
        schemas: passwordFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      })
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields()
        setModalProps({ confirmLoading: false })
        rowId.value = data.id
        setFieldsValue({
          ...data,
        })
      })
      const getTitle = ref('修改密码')
      async function handleSubmit() {
        try {
          const values = await validate()
          setModalProps({ confirmLoading: true })
          updatePassword(values)
            .then(() => message.success(t('sys.api.successMessage')))
            .catch((error) => {
              createErrorModal({
                title: t('sys.api.errorTip'),
                content: (error as unknown as Error).message || t('sys.api.networkExceptionMsg'),
              })
            })
          closeModal()
        } finally {
          setModalProps({ confirmLoading: false })
        }
      }
      return { registerModal, registerForm, getTitle, handleSubmit }
    },
  })
</script>
